/**
 * 新的安全SSE (Server-Sent Events) 服务
 * 重新设计的实时告警推送客户端
 */

export interface AlertData {
  id: number
  title: string
  hostname: string
  severity: string
  status: string
  event_time: string
  zabbix_server: string
  description: string
  host_ip: string
}

export interface MessageHandler {
  (data: AlertData): void
}

export interface SSEConnectionState {
  isConnected: boolean
  connectionCount: number
  lastHeartbeat: string | null
  reconnectAttempts: number
  error: string | null
}

class SafeSSEService {
  private eventSource: EventSource | null = null
  private reconnectAttempts = 0
  private maxReconnectAttempts = 3  // 减少重连次数，避免过度重连
  private reconnectInterval = 10000  // 10秒基础间隔，增加延迟
  private maxReconnectInterval = 60000 // 60秒最大间隔
  private _isConnected = false
  private connectionId: string | null = null
  private lastHeartbeat: string | null = null
  private messageHandlers: MessageHandler[] = []
  private connectHandlers: (() => void)[] = []
  private disconnectHandlers: (() => void)[] = []
  private errorHandlers: ((error: Event) => void)[] = []
  private reconnectTimer: number | null = null
  public hasShownConnectedMessage: boolean = false

  /**
   * 连接到SSE服务器 - 安全版本
   */
  connect(token: string): void {
    // 防止重复连接
    if (this.eventSource && this._isConnected) {
      console.log('SSE已连接，跳过重复连接请求')
      return
    }

    // 检查是否超过最大重连次数
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.log('SSE重连次数已达上限，停止重连')
      return
    }

    // 清理现有连接
    this.disconnect()

    try {
      const url = `${import.meta.env.VITE_API_URL}/api/monitoring/sse/alerts/stream/?token=${token}`
      console.log('正在建立安全SSE连接:', url)

      this.eventSource = new EventSource(url)

      this.eventSource.onopen = () => {
        console.log('安全SSE连接已建立')
        this._isConnected = true
        this.reconnectAttempts = 0
        this.clearReconnectTimer()
        this.connectHandlers.forEach(handler => handler())
      }

      this.eventSource.addEventListener('connected', (event) => {
        try {
          const data = JSON.parse(event.data)
          this.connectionId = data.connection_id
          console.log('SSE连接确认:', data)
        } catch (error) {
          console.error('解析连接确认消息失败:', error)
        }
      })

      this.eventSource.addEventListener('heartbeat', (event) => {
        try {
          const data = JSON.parse(event.data)
          this.lastHeartbeat = data.timestamp
          console.log('收到心跳:', data)
        } catch (error) {
          console.error('解析心跳消息失败:', error)
        }
      })

      this.eventSource.addEventListener('new_alert', (event) => {
        try {
          const alertData = JSON.parse(event.data)
          console.log('收到新告警:', alertData)
          this.messageHandlers.forEach(handler => handler(alertData))
        } catch (error) {
          console.error('解析告警数据失败:', error)
        }
      })

      this.eventSource.addEventListener('test_alert', (event) => {
        try {
          const alertData = JSON.parse(event.data)
          console.log('收到测试告警:', alertData)
          this.messageHandlers.forEach(handler => handler(alertData))
        } catch (error) {
          console.error('解析测试告警数据失败:', error)
        }
      })

      this.eventSource.onerror = (error) => {
        console.error('SSE连接错误:', error)
        this._isConnected = false
        this.errorHandlers.forEach(handler => handler(error))

        // 智能重连策略
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
          this.scheduleReconnect(token)
        } else {
          console.error('SSE重连次数已达上限，停止重连')
          this.disconnect()
        }
      }

    } catch (error) {
      console.error('创建SSE连接失败:', error)
      this._isConnected = false
    }
  }

  /**
   * 安全断开SSE连接
   */
  disconnect(): void {
    console.log('正在断开SSE连接...')

    this.clearReconnectTimer()

    if (this.eventSource) {
      this.eventSource.close()
      this.eventSource = null
    }

    this._isConnected = false
    this.connectionId = null
    this.reconnectAttempts = 0
    this.lastHeartbeat = null

    this.disconnectHandlers.forEach(handler => handler())
    console.log('SSE连接已断开')
  }

  /**
   * 清理重连定时器
   */
  private clearReconnectTimer(): void {
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer)
      this.reconnectTimer = null
    }
  }

  /**
   * 智能重连调度
   */
  private scheduleReconnect(token: string): void {
    this.clearReconnectTimer()

    this.reconnectAttempts++
    const delay = Math.min(
      this.reconnectInterval * Math.pow(2, this.reconnectAttempts - 1),
      this.maxReconnectInterval
    )

    console.log(`SSE将在 ${delay}ms 后进行第 ${this.reconnectAttempts} 次重连`)

    this.reconnectTimer = window.setTimeout(() => {
      if (!this._isConnected && this.reconnectAttempts <= this.maxReconnectAttempts) {
        this.connect(token)
      }
    }, delay)
  }

  /**
   * 添加消息处理器
   */
  onMessage(handler: MessageHandler): void {
    this.messageHandlers.push(handler)
  }

  /**
   * 移除消息处理器
   */
  offMessage(handler: MessageHandler): void {
    const index = this.messageHandlers.indexOf(handler)
    if (index > -1) {
      this.messageHandlers.splice(index, 1)
    }
  }

  /**
   * 添加连接处理器
   */
  onConnect(handler: () => void): void {
    this.connectHandlers.push(handler)
  }

  /**
   * 添加断开连接处理器
   */
  onDisconnect(handler: () => void): void {
    this.disconnectHandlers.push(handler)
  }

  /**
   * 添加错误处理器
   */
  onError(handler: (error: Event) => void): void {
    this.errorHandlers.push(handler)
  }

  /**
   * 获取连接状态
   */
  get isConnected(): boolean {
    return this._isConnected
  }

  /**
   * 获取连接状态信息
   */
  getConnectionState(): SSEConnectionState {
    return {
      isConnected: this._isConnected,
      connectionCount: this._isConnected ? 1 : 0,
      lastHeartbeat: this.lastHeartbeat,
      reconnectAttempts: this.reconnectAttempts,
      error: null
    }
  }

  /**
   * 重置连接状态
   */
  reset(): void {
    this.disconnect()
    this.messageHandlers = []
    this.connectHandlers = []
    this.disconnectHandlers = []
    this.errorHandlers = []
  }
}

// 导出单例实例
export const sseService = new SafeSSEService()

export type { AlertData, MessageHandler, SSEConnectionState }
